import { userApi } from '@/constants';
import { get, post, put, patch, del } from '@/util/api';

// 用户基本信息接口
export interface UserBase {
  username: string;
  nickname?: string;
  email?: string;
  phone?: string;
  avatar?: string;
  role?: number; // 0普通用户，1管理员
  status?: number; // 0禁用，1启用
}

// 用户响应接口
export interface User extends UserBase {
  id: number;
  createdAt: string;
  updatedAt: string;
  password?: string;
  lastLoginAt?: string;
  articleCount?: number;
  commentCount?: number;
}

// 用户列表响应接口
export interface UserListResponse {
  data: User[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

// 用户操作日志接口
export interface UserLog {
  id: number;
  userId: number;
  action: string;
  description: string;
  ip: string;
  userAgent: string;
  createdAt: string;
}

/**
 * 用户管理服务类
 */
class UserService {
  /**
   * 获取用户列表
   */
  async getUserList(params?: {
    page?: number;
    pageSize?: number;
    keyword?: string;
    role?: number;
    status?: number;
    startDate?: string;
    endDate?: string;
  }) {
    return get(userApi.LIST, { params });
  }

  /**
   * 获取用户详情
   */
  async getUserDetail(id: number): Promise<User> {
    const response = await get(userApi.DETAIL(id));
    return (response.data || response) as User;
  }

  /**
   * 创建用户
   */
  async createUser(userData: Partial<UserBase>): Promise<User> {
    const response = await post(userApi.CREATE, userData);
    return (response.data || response) as User;
  }

  /**
   * 更新用户信息
   */
  async updateUser(id: number, userData: Partial<UserBase>): Promise<User> {
    const response = await put(userApi.UPDATE(id), userData);
    return (response.data || response) as User;
  }

  /**
   * 更新用户角色
   */
  async updateUserRole(id: number, role: number): Promise<User> {
    return this.updateUser(id, { role });
  }

  /**
   * 更新用户状态
   */
  async updateUserStatus(id: number, status: number): Promise<User> {
    const response = await put(userApi.UPDATE_STATUS(id), { status });
    return (response.data || response) as User;
  }

  /**
   * 重置用户密码
   */
  async resetPassword(id: number, newPassword: string): Promise<void> {
    await put(userApi.RESET_PASSWORD(id), { password: newPassword });
  }

  /**
   * 删除用户
   */
  async deleteUser(id: number): Promise<void> {
    await del(userApi.DELETE(id));
  }

  /**
   * 批量操作用户
   */
  async batchOperateUsers(ids: number[], action: string, data?: any) {
    const response = await patch(userApi.BATCH_OPERATE, { ids, action, ...data });
    return response.data || response;
  }

  /**
   * 获取用户操作日志
   */
  async getUserLogs(userId: number, params?: {
    page?: number;
    pageSize?: number;
    action?: string;
  }) {
    const response = await get(userApi.USER_LOGS(userId), { params });
    return response.data || response;
  }
}

export const userService = new UserService();
export default userService;